<?php
namespace app\home\logic;

use think\Model;

class Baopay extends Model {
    public $member_id, $terminal_id, $md5_key, $pay_url, $page_url, $return_url, $type;

    public function initialize() {
        parent::initialize();
        $this->type = 1;//0线下支付1线上支付
        //测试
        //$this->member_id = 100000178;    //商户号
        //$this->terminal_id = 10000001;    //终端号
        //$this->md5_key = 'abcdefg';    //商户秘钥
        //$this->pay_url = 'https://vgw.baofoo.com/payindex';

        //正式
        $this->member_id = 1189942;    //商户号
        $this->terminal_id = 36295;    //终端号
        $this->md5_key = 'a4vgcg9c3mszavl9';    //商户秘钥
        $this->pay_url = 'https://gw.baofoo.com/payindex';

        $this->page_url = url('charge/callback', 'payment=baopay', true, true);
        $this->return_url = url('charge/callback', 'payment=baopay', true, true);
    }

    public function submit($data) {
        if (!isset($data['money']) || !is_numeric($data['money']) || $data['money'] <= 0) {
            return ['code' => 0, 'msg' => '金额有误!'];
        }

        $arr["MemberID"] = $this->member_id;//商户号
        $arr["TerminalID"] = $this->terminal_id;//终端号
        $arr["PayID"] = isset($_POST["PayID"]) ? $_POST["PayID"] : "";//
        $arr["TradeDate"] = $this->return_time();//日期时间
        $arr["TransID"] = isset($data['trade_no']) ? $data['trade_no'] : $this->get_transid();//商户订单号

        $Money = $data['money'];//接收金额

        $arr["OrderMoney"] = (int) ($Money * 100);//订单金额(以分为单位)
        $arr["InterfaceVersion"] = "4.0";
        $arr["ProductName"] = "充值";
        $arr["Amount"] = "1";//商户数量
        $arr["UserName"] = "";
        $arr["AdditionalInfo"] = "";
        $arr["PageUrl"] = $this->page_url;//页面跳转地址（改成商户自已的地址）
        $arr["ReturnUrl"] = $this->return_url;//服务器通知地址(改成商户自己的接收通知地址。)
        $arr["KeyType"] = "1";
        $arr["NoticeType"] = "1";//1：页面通知+异步通知；0：异步通知

        $Md5Key = $this->md5_key;//商户钥钥
        $MARK = "|";
        $Md5String = $arr["MemberID"] . $MARK . $arr["PayID"] . $MARK . $arr["TradeDate"] . $MARK . $arr["TransID"] . $MARK . $arr["OrderMoney"] . $MARK . $arr["PageUrl"] . $MARK . $arr["ReturnUrl"] . $MARK . $arr["NoticeType"] . $MARK . $Md5Key;
        $this->LogWirte($Md5String);
        $arr["Signature"] = md5($Md5String);//签名字段
        $arr["actform"] = $this->pay_url;//请求地址

        $ReturnString = '<body onLoad="document.actform.submit()">正在处理请稍候............................'
                . '<form  id="actform" name="actform" method="post" action="' . $arr["actform"] . '">'
                . '<input name="MemberID" type="hidden" value="' . $arr["MemberID"] . '"/>'
                . '<input name="TerminalID" type="hidden" value="' . $arr["TerminalID"] . '"/>'
                . '<input name="PayID" type="hidden" value="' . $arr["PayID"] . '"/>'
                . '<input name="InterfaceVersion" type="hidden" value="' . $arr["InterfaceVersion"] . '"/>'
                . '<input name="KeyType" type="hidden"  value="' . $arr["KeyType"] . '"/>'
                . '<input name="TradeDate" type="hidden"  value="' . $arr["TradeDate"] . '"/>'
                . '<input name="TransID" type="hidden"  value="' . $arr["TransID"] . '"/>'
                . '<input name="OrderMoney" type="hidden"  value="' . $arr["OrderMoney"] . '"/>'
                . '<input name="ProductName" type="hidden"  value="' . $arr["ProductName"] . '"/>'
                . '<input name="Username" type="hidden"  value="' . $arr["UserName"] . '"/>'
                . '<input name="AdditionalInfo" type="hidden"  value="' . $arr["AdditionalInfo"] . '"/>'
                . '<input name="NoticeType" type="hidden"  value="' . $arr["NoticeType"] . '"/>'
                . '<input name="PageUrl" type="hidden"  value="' . $arr["PageUrl"] . '"/>'
                . '<input name="ReturnUrl" type="hidden"  value="' . $arr["ReturnUrl"] . '"/>'
                . '<input name="Signature" type="hidden"  value="' . $arr["Signature"] . '"/>'
                . '</form></body>';
//echo $ReturnString;exit;
        return ['code' => 1, 'msg' => $arr];
    }

    public function test($data) {
        if (!isset($data['money']) || !is_numeric($data['money']) || $data['money'] <= 0) {
            return ['code' => 0, 'msg' => '金额有误!'];
        }

        $arr["MemberID"] = $this->member_id;//商户号
        $arr["TerminalID"] = $this->terminal_id;//终端号
        $arr["PayID"] = isset($_POST["PayID"]) ? $_POST["PayID"] : "";//
        $arr["TradeDate"] = $this->return_time();//日期时间
        $arr["TransID"] = isset($data['trade_no']) ? $data['trade_no'] : $this->get_transid();//商户订单号

        $Money = $data['money'];//接收金额

        $arr["OrderMoney"] = (int) ($Money * 100);//订单金额(以分为单位)
        $arr["InterfaceVersion"] = "4.0";
        $arr["ProductName"] = "充值";
        $arr["Amount"] = "1";//商户数量
        $arr["UserName"] = "支付用户名称";
        $arr["AdditionalInfo"] = "附加信息";
        $arr["PageUrl"] = $this->page_url;//页面跳转地址（改成商户自已的地址）
        $arr["ReturnUrl"] = $this->return_url;//服务器通知地址(改成商户自己的接收通知地址。)
        $arr["KeyType"] = "1";
        $arr["NoticeType"] = "1";//1：页面通知+异步通知；0：异步通知

        $Md5Key = $this->md5_key;//商户钥钥
        $MARK = "|";
        $Md5String = $arr["MemberID"] . $MARK . $arr["PayID"] . $MARK . $arr["TradeDate"] . $MARK . $arr["TransID"] . $MARK . $arr["OrderMoney"] . $MARK . $arr["PageUrl"] . $MARK . $arr["ReturnUrl"] . $MARK . $arr["NoticeType"] . $MARK . $Md5Key;

        $this->LogWirte($Md5String);

        $arr["Signature"] = md5($Md5String);//签名字段
        $payUrl = $this->pay_url;//请求地址

        $ReturnString = '<body onLoad="document.actform.submit()">正在处理请稍候............................'
                . '<form  id="actform" name="actform" method="post" action="' . $payUrl . '">'
                . '<input name="MemberID" type="hidden" value="' . $arr["MemberID"] . '"/>'
                . '<input name="TerminalID" type="hidden" value="' . $arr["TerminalID"] . '"/>'
                . '<input name="PayID" type="hidden" value="' . $arr["PayID"] . '"/>'
                . '<input name="InterfaceVersion" type="hidden" value="' . $arr["InterfaceVersion"] . '"/>'
                . '<input name="KeyType" type="hidden"  value="' . $arr["KeyType"] . '"/>'
                . '<input name="TradeDate" type="hidden"  value="' . $arr["TradeDate"] . '"/>'
                . '<input name="TransID" type="hidden"  value="' . $arr["TransID"] . '"/>'
                . '<input name="OrderMoney" type="hidden"  value="' . $arr["OrderMoney"] . '"/>'
                . '<input name="ProductName" type="hidden"  value="' . $arr["ProductName"] . '"/>'
                . '<input name="Username" type="hidden"  value="' . $arr["UserName"] . '"/>'
                . '<input name="AdditionalInfo" type="hidden"  value="' . $arr["AdditionalInfo"] . '"/>'
                . '<input name="NoticeType" type="hidden"  value="' . $arr["NoticeType"] . '"/>'
                . '<input name="PageUrl" type="hidden"  value="' . $arr["PageUrl"] . '"/>'
                . '<input name="ReturnUrl" type="hidden"  value="' . $arr["ReturnUrl"] . '"/>'
                . '<input name="Signature" type="hidden"  value="' . $arr["Signature"] . '"/>'
                . '</form></body>';

        echo $ReturnString;
        exit;
    }

    function get_transid() {//生成时间戳

        return strtotime(date('Y-m-d H:i:s', time()));

    }

    function rand4() {//生成四位随机数

        return rand(1000, 9999);

    }

    function return_time() {//生成时间

        return date('YmdHis', time());

    }

    public function callback($data = []) {
        $MemberID = $_REQUEST['MemberID'];//商户号
        $TerminalID = $_REQUEST['TerminalID'];//商户终端号
        $TransID = $_REQUEST['TransID'];//流水号
        $Result = $_REQUEST['Result'];//支付结果
        $ResultDesc = $_REQUEST['ResultDesc'];//支付结果描述
        $FactMoney = $_REQUEST['FactMoney'];//实际成功金额
        $AdditionalInfo = $_REQUEST['AdditionalInfo'];//订单附加消息
        $SuccTime = $_REQUEST['SuccTime'];//支付完成时间
        $Md5Sign = $_REQUEST['Md5Sign'];//md5签名
        $Md5key = $this->md5_key;//商户密钥
        $MARK = "~|~";

        //MD5签名格式
        $sign = 'MemberID=' . $MemberID . $MARK . 'TerminalID=' . $TerminalID . $MARK . 'TransID=' . $TransID . $MARK . 'Result=' . $Result . $MARK . 'ResultDesc=' . $ResultDesc . $MARK . 'FactMoney=' . $FactMoney . $MARK . 'AdditionalInfo=' . $AdditionalInfo . $MARK . 'SuccTime=' . $SuccTime . $MARK . 'Md5Sign=' . $Md5key;

        $this->LogWirte($sign);

        $WaitSign = md5($sign);
        if ($Md5Sign == $WaitSign) {
            db()->startTrans();
            if ($Result == 1 && $ResultDesc == '01') {
                $re = model('charge', 'logic')->OnlineReturn(['trade_no' => $TransID, 'sign' => $sign]);
            } else {
                $re = model('charge', 'logic')->OnlineReturnNo(['trade_no' => $TransID, 'sign' => $sign]);
            }
            if ($re) {
                db()->commit();
            } else {
                db()->rollback();
            }
            die ("OK");//全部正确了输出OK
        } else {
            die('非法访问!');//MD5校验失败
            //处理想处理的事情
        }

    }
    public function LogWirte($Astring)
    {
        $path = LOG_PATH."baopay/";
        $file = $path.date('Ymd',time()).".txt";
        if(!is_dir($path)){	mkdir($path); }
        $LogTime = date('Y-m-d H:i:s',time());
        if(!file_exists($file))
        {
            $logfile = fopen($file, "w") or die("Unable to open file!");
            fwrite($logfile, "[$LogTime]:".$Astring."\r\n");
            fclose($logfile);
        }else{
            $logfile = fopen($file, "a") or die("Unable to open file!");
            fwrite($logfile, "[$LogTime]:".$Astring."\r\n");
            fclose($logfile);
        }
    }
}
